package com.blog.controller;

import com.blog.entity.User;
import com.blog.service.UserService;
import com.wf.captcha.utils.CaptchaUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Api(tags = "用户-登录控制器")
@Controller
//@RequestMapping("/user")
public class LoginController {

    @Autowired
    private UserService userService;

    @ApiOperation("直接请求则直接跳转")
    @GetMapping("login")
    public String loginPage(){
        //HttpServletRequest request
        //String uri = request.getRequestURI();
        //uri.endsWith("/login")
        //服务器上不要加斜杠/跳转
        //否则会报错：Error resolving template [/login], template might not exist or might not be accessible by any of the configured Template Resolvers
//        return "/login";
        return "login";
    }

    @ApiOperation("登录检测")
    @PostMapping("/login")
    public String login(@RequestParam String captcha,
                        @RequestParam String username, @RequestParam String password,
                        HttpSession session, HttpServletRequest request, RedirectAttributes attributes) {

        //先判断验证码
        if (!CaptchaUtil.ver(captcha, request)) {
            CaptchaUtil.clear(request);  // 清除session中的验证码
            attributes.addFlashAttribute("message","验证码有误!!! ");     //将信息添加到缓存中，避免重定向数据丢失
            return "redirect:/login";
        }

        //DB匹配用户信息
        User user = userService.checkUserByEmailAndPassword(username,password);
        if(user != null){
            //帐号被封，直接跳转
            if(!user.isEnabled()){
                attributes.addFlashAttribute("message","帐号被封，请联系管理员处理!!! ");     //将信息添加到缓存中，避免重定向数据丢失
                return "redirect:/login";
            }
            //避免多人同时登录同一浏览器
            session.removeAttribute("user");

            session.setAttribute("user",user);
            return "redirect:/oneUser/-1/"+user.getId();
        }else{
            attributes.addFlashAttribute("message","用户名或密码有误!!! ");     //将信息添加到缓存中，避免重定向数据丢失
            return "redirect:/login";
        }
    }

    @ApiOperation("退出-注销操作")
    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute("user");
        return "redirect:/";
    }


    @ApiOperation("跳转到验证码登录页")
    @GetMapping("/loginByCode")
    public String toLoginByCode(){
        return "loginCode";
    }

    @ApiOperation("验证码登录")
    @PostMapping("/loginByCode")
    public String loginByCode(@RequestParam String username, @RequestParam String code,
                        HttpSession session, HttpServletRequest request,
                        Model model, RedirectAttributes attributes) {

        User user = userService.selectUserByEmail(username);
        //判断是获取验证码还是登录
        if (StringUtils.isEmpty(code)) {
            //先检查邮箱是否已注册
            if (user == null) {
                model.addAttribute("message", "该邮箱尚未注册，请先注册!!! ");
                return "loginCode";
            } else if (!user.isEnabled()) {
                attributes.addFlashAttribute("message", "帐号被封，请联系管理员处理!!! ");
                return "redirect:/loginCode";
            }
            //再发送邮箱验证码
            int sentRes = userService.checkEmailCode(username);
            if (sentRes == 1) {
                model.addAttribute("message", "邮件发送成功，请注意查收!!! ");     //将信息添加到缓存中，避免重定向数据丢失
            } else {
                model.addAttribute("message", "请忽重复发送邮件!!! ");
            }
            model.addAttribute("email", username);
            return "loginCode";
        } else {
            int res = userService.checkEmailAndCode(username, code);
            if (res == 1) {
                //登录成功-存session－跳转到个人中心
                session.removeAttribute("user");
                session.setAttribute("user",user);
                return "redirect:/oneUser/-1/"+user.getId();
            } else {
                //登录失败
                attributes.addFlashAttribute("message", "用户名或密码有误!!! ");     //将信息添加到缓存中，避免重定向数据丢失
                return "redirect:/loginCode";
            }
        }
    }


}
